package com.wzc.basic.util;

import com.wzc.basic.jwt.JwtUtils;
import com.wzc.basic.jwt.Payload;
import com.wzc.basic.jwt.RsaUtils;
import com.wzc.user.domain.Logininfo;
import com.wzc.user.util.LoginData;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

public class LoginContext {
    /**
     * 返回当前登录人的信息
     */
    public static Logininfo getLogininfo(HttpServletRequest request){
        try {
            String jwtToken = request.getHeader("token"); // 获取请求头中的token
            if(jwtToken != null) { // 请求头中有token
                // 解密
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());

                //4.将jwtToken解析成想要的数据：LoginData
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, LoginData.class);

                if (payload != null) {//登录成功，而且没有过期
                    // 5. 获取登录信息对象
                    Logininfo logininfo = payload.getLoginData().getLogininfo();
                    return logininfo;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
